package com.my.study.groovy;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;

import java.io.File;
import java.io.IOException;

/**
 * @author yidujun
 * @version 1.0.0
 * @date 2023/7/30 16:13
 */
public class GroovyFactory {
    
    private static final GroovyFactory FACTORY = new GroovyFactory();
    
    private GroovyClassLoader groovyClassLoader = new GroovyClassLoader();

    public static GroovyFactory getInstance() {
        return FACTORY;
    }
    
    public IRule getIRuleFromPackage(String filePath) throws IllegalAccessException, InstantiationException, IOException {
        File file = new File(filePath);
        Class clazz = groovyClassLoader.parseClass(new GroovyCodeSource(file));
        if (clazz != null) {
            Object obj = clazz.newInstance();
            if (obj instanceof IRule) {
                return ((IRule) obj);
            }
        }
        throw new IllegalArgumentException("读取Groovy文件异常。");
    }
    
    
    
}
